<script setup>
import {ref} from "vue";
import {login} from "@/api/request.js";
import router from "@/router/index.js";
import {useUserStore} from "@/store/user.js";
import {showToast} from "vant";

const phone = ref('')
const password = ref('')

const store = useUserStore()

const onClickLeft = () => {
  router.push('/')
}

const onSubmit = async () => {
  await login({phone:phone.value, password: password.value}).then(res => {
    const user = res.data
    if (user === null) {
      showToast('没有返回数据')
      return false
    }

    store.userId = user.id
    store.username = user.username
    store.avatar = user.avatar
    store.isAuthenticated = true

    router.push('/')
  })
}
</script>

<template>
  <van-nav-bar left-arrow @click-left="onClickLeft"/>

  <div class="login-page">
    <div class="login-content">
      <van-nav-bar>
        <template #title>
          <div class="title">登录</div>
        </template>
      </van-nav-bar>
      <van-form @submit="onSubmit">
        <van-field v-model="phone" :rules="[{ required: true, message: '请填写手机号' }]" label="手机号" name="username"
                   placeholder="用户名"/>
        <van-field v-model="password" :rules="[{ required: true, message: '请填写密码' }]" label="密码" name="password" placeholder="密码"
                   type="password"/>
        <div style="margin: 16px">
          <van-button block native-type="submit" type="primary">登录</van-button>
        </div>
      </van-form>
      <router-link class="link" to="/register">还没有账号,去注册</router-link>
    </div>
  </div>
</template>

<style lang="less" scoped>
.login-page {
  width: 100%;
  height: 80vh;
  display: flex;
  overflow: hidden;
  background-repeat: no-repeat;
  background-size: cover;
  opacity: 0.9;

  .login-content {
    margin: auto;
    padding: 10px 10px 20px 10px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    opacity: 0.9;

    .title {
      font-size: 20px;
      font-weight: 600;
    }
  }

  .link {
    font-size: 12px;
    color: #069;
    float: right;
    margin-right: 15px;
  }
}

</style>